package service

import (
	"errors"
	"fmt"
	"shoping.zozoo.net/dao"
	"shoping.zozoo.net/model"
	"shoping.zozoo.net/params"
	"shoping.zozoo.net/tool"
	"time"
)

//定义接口
type ProductInterface interface {
	GetProductById(int64) (*model.Product, error)
	GetAllProduct() ([]*model.Product, error)
	DelProductById(int64) (bool, error)
	InsertProduct(*params.ProductParam) (int64, error)
	UpdateProduct() error
	Seckill(*params.Seckill) (*model.Order, error)
}

type ProductService struct {
	dao dao.ProductInterface
}

func NewProductService(d dao.ProductInterface) ProductInterface {
	return &ProductService{
		d,
	}
}

//获取产品详情
func (p *ProductService) GetProductById(id int64) (product *model.Product, err error) {
	product = new(model.Product)
	return p.dao.SelectById(id)
}

//获取产品列表
func (p *ProductService) GetAllProduct() (list []*model.Product, err error) {
	return p.dao.SelectAll()
}

func (p *ProductService) DelProductById(id int64) (ok bool, err error) {
	return
}

//添加产品
func (p *ProductService) InsertProduct(param *params.ProductParam) (id int64, err error) {
	var (
		product *model.Product
	)

	product = &model.Product{
		ProductName:  param.ProductName,
		ProductNum:   param.ProductNum,
		ProductImage: param.ProductImage,
		ProductUrl:   param.ProductUrl,
	}

	if _, err = p.dao.Insert(product); err != nil {
		return 0, err
	}

	return product.Id, nil
}

//修改产品
func (p *ProductService) UpdateProduct() (err error) {
	return
}

//秒杀商品
func (p *ProductService) Seckill(param *params.Seckill) (order *model.Order, err error) {
	var (
		product *model.Product
		o       dao.OrderInterface
		orderId int64
	)

	//判断商品库存
	if product, err = p.dao.SelectById(param.ProductId); err != nil {
		return nil, err
	}
	if product.Id == 0 {
		return nil, errors.New("商品不存在")
	}
	if product.ProductNum < 1 {
		return nil, errors.New("商品已经抢购一空")
	}

	//减商品库存
	product.ProductNum -= 1
	if err = p.dao.Update(product); err != nil {
		return nil, err
	}

	//创建订单
	order = &model.Order{
		UserId:    param.UserId,
		ProductId: param.ProductId,
		Status:    1,
		OrderNum:  fmt.Sprintf("%v", time.Now().UnixNano()),
	}
	o = dao.NewOrderDao(tool.DbEngine)
	if orderId, err = o.InsertOrder(order); err != nil {
		return nil, err
	}
	if orderId == 0 {
		return nil, errors.New("创建订单失败")
	}

	return
}
